package com.lesshassles.controller;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.lesshassles.model.UserBroker;
import com.lesshassles.model.User;
import com.lesshassles.util.ApplicationSecurityManager;

public class SignInController extends SimpleFormController {
	private UserBroker userBroker;
	private ApplicationSecurityManager applicationSecurityManager;

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new User();
	}

	/** Forwards to success view, if already logged in */
	public ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors, Map controlModel)
			throws Exception {
		if (applicationSecurityManager.getUser(request) != null)
			return new ModelAndView(getSuccessView());

		return super.showForm(request, response, errors, controlModel);
	}

	/** Validates user/password against database */
	public void onBindAndValidate(HttpServletRequest request, Object command,
			BindException errors) throws Exception {
		if (errors.hasErrors())
			return;

		User formUser = (User) command;
		
		User dbUser = (User) command;
		
		dbUser = userBroker.getUserByLogin(formUser.getEmail(), formUser.getPassword());
		
		if (dbUser == null) {
			errors.reject("error.login.invalid");
		} else {
			applicationSecurityManager.setUser(request, dbUser);
		}
	}

	/** returns ModelAndView(getSuccessView()) */
	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		return new ModelAndView(getSuccessView());
	}

	public UserBroker getUserBroker() {
		return userBroker;
	}
	public void setUserBroker(UserBroker userBroker) {
		this.userBroker = userBroker;
	}

	public ApplicationSecurityManager getApplicationSecurityManager() {
		return applicationSecurityManager;
	}
	public void setApplicationSecurityManager(
			ApplicationSecurityManager applicationSecurityManager) {
		this.applicationSecurityManager = applicationSecurityManager;
	}
}
